from app.core.aes_util import AESCipher
from app.core.config import settings
from typing import Optional, List
import time
import hmac
import hashlib
import base64
from app.core.logger import logger
from app.core.http_client import HttpClient
import json
from app.schemas.waveup.trading_pair import WPProductSwapReq
from app.core.utils import gen_order_no

"""生成WaveUp接口请求签名"""
async def generate_signature(path: str, query: str, body: str) -> str:
    """异步AES加密"""
    # 毫秒级时间戳
    timestamp = int(time.time()*1000)

    signingStr = f"{timestamp}\n{path}?{query}\n{body}"
    logger.info(f"signingStr: {signingStr}")
    """计算签名"""
    hmacSha256 = hmac.new(settings.WP_APP_SECRET.encode('utf-8'), signingStr.encode('utf-8'), hashlib.sha256)
    signature = hmacSha256.digest()
    """Base64编码"""
    signature = base64.b64encode(signature).decode('utf-8')
    """字符串替换：+替换为-，将/替换为_"""
    signature = signature.replace("+", "-").replace("/", "_")
    retData = f"Basic {settings.WP_APP_KEY}:{timestamp}:{signature}"
    logger.info(f"retData: {retData}")

    return retData

async def encrypt_data(data: str) -> str:
    """创建AES加密器"""
    key = settings.WP_APP_SECRET.encode('utf-8')[:16]
    iv = settings.WP_APP_SECRET.encode('utf-8')[:16]
    cipher = AESCipher(key, iv, padding="zero")
    """加密数据"""
    encrypted_data = cipher.encrypt(data)
    logger.info(f"encrypted_data: {encrypted_data}")
    return encrypted_data

async def decrypt_data(encrypted_data: str) -> str:
    """创建AES解密器"""
    key = settings.WP_APP_SECRET.encode('utf-8')[:16]
    iv = settings.WP_APP_SECRET.encode('utf-8')[:16]
    cipher = AESCipher(key, iv, padding="zero")
    """解密数据"""
    decrypted_data = cipher.decrypt(encrypted_data)
    logger.info(f"decrypted_data: {decrypted_data}")
    return decrypted_data

async def query_wp_products(pageNo: int = 1, pageSize: int = 100, productIds: Optional[List[str]] = None):
    """查询WaveUp藏品列表"""
    path = settings.WP_QUERY_PRODUCTS
    query = ""
    body = {
        "pageNo": pageNo,
        "pageSize": pageSize,
    }
    if productIds:
        body["productIds"] = productIds
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json;charset=utf-8"
    }

    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': {'pageNo': 1, 'pageSize': 2, 'total': 2, 'totalPage': 1, 'records': [{'productId': '1945319365610057730', 'productName': 'WaveUP测试藏品-银', 'imageUrl': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/9fc4c9cf11464e9789931e419ccc08e8.png', 'detailUrl': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/527cd7aad64b47aea225c628adc4d767.png', 'description': '1', 'issueAmount': '5000000'}, {'productId': '1945318928026710018', 'productName': 'WaveUP测试藏品-金', 'imageUrl': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/e66173aaa6d047a580b017d585e92d02.png', 'detailUrl': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/a6905abe02bc41fe9d3fd34a83f4d39e.png', 'description': '1', 'issueAmount': '5000000'}]}, 'rc': 0, 'success': True}
    return response

async def query_wp_product_pair(
    pageNo: int = 1, 
    pageSize: int = 100, 
    tradeStatusList: Optional[List[int]] = None
):
    """查询WaveUp藏品对列表"""
    # tradeStatus: 0待投票, 1投票中, 2 待开放, 3投票失败, 4开放中, 5：已停牌
    path = settings.WP_QUERY_PRODUCT_PAIR
    query = ""
    body = {
        "pageNo": pageNo,
        "pageSize": pageSize,
        "start": 0
    }
    if tradeStatusList:
        body["tradeStatusList"] = tradeStatusList
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': {'pageNo': 1, 'pageSize': 10, 'total': 6, 'totalPage': 1, 'records': [{'productPairId': '1968514513915015169', 'productPairName': '敦煌美术研究所幸运飞天-天宝·龙珠', 'tradeStatus': 4, 'productIdA': '1903840410895118338', 'productNameA': '敦煌美术研究所幸运飞天', 'productImageA': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/8b5b3bf8d7754cdd9e819fb20be35d5d.jpg', 'lockAmountA': '534.6292398', 'productIdB': '1967461585288622082', 'productNameB': '天宝·龙珠', 'productImageB': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/09/19/1410cdc6141e4a6492f12981083415b2sync/6d7032f464c84553805c8030c3be3364.jpg', 'lockAmountB': '2241.6728795', 'lockAmountK': '1198463.86744736', 'platformFeeRate': '0.005', 'poolFeeRate': '0.005', 'slipPageRange': '0.05,0.10,0.20#0.01,0.5'}, {'productPairId': '1965281951363760130', 'productPairName': 'WaveUP测试藏品-金-WaveUP测试藏品-银', 'tradeStatus': 4, 'productIdA': '1945318928026710018', 'productNameA': 'WaveUP测试藏品-金', 'productImageA': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/e66173aaa6d047a580b017d585e92d02.png', 'lockAmountA': '16730.17704952', 'productIdB': '1945319365610057730', 'productNameB': 'WaveUP测试藏品-银', 'productImageB': 'https://waveup.oss-cn-hangzhou.aliyuncs.com/images/2025/07/26/9fc4c9cf11464e9789931e419ccc08e8.png', 'lockAmountB': '994.98656189', 'lockAmountK': '16646301.34231289', 'platformFeeRate': '0.005', 'poolFeeRate': '0.005', 'slipPageRange': '0.05,0.10,0.20#0.01,0.5'}]}, 'rc': 0, 'success': True}
    return response

async def query_wp_wallet(
    pageNo: int = 1, 
    pageSize: int = 100, 
    accessToken: str = "", 
    productIds: Optional[List[str]] = None
):
    """查询WaveUp钱包列表"""
    path = settings.WP_QUERY_WALLET
    query = ""
    body = {
        "accessToken": accessToken,
        "pageNo": pageNo,
        "pageSize": pageSize,
    }
    if productIds:
        body["productIds"] = productIds
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': {'pageNo': 1, 'pageSize': 100, 'total': 0, 'totalPage': 0, 'records': []}, 'rc': 0, 'success': True}
    return response

# 藏品兑换
# 1、fromAmount*(1-手续费比例)=实际fromAmount
# 2、(池子中A的数量+实际fromAmount) * (池子中b的数量-toAmount)=池子k值
async def wp_product_swap(req: WPProductSwapReq, uid: int):
    """藏品对交易"""
    path = settings.WP_PRODUCT_SWAP
    query = ""
    body = req.model_dump()
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': {'id': '1988439680494415873', 'amountA': '16.63766682', 'amountB': '1', 'exchangeType': 1, 'dealValue': '597', 'fee': '0.01'}, 'rc': 0, 'success': True}
    return response

async def get_wp_access_token(userAuthCode: str):
    """获取WaveUp访问令牌"""
    path = settings.WP_GET_ACCESS_TOKEN
    query = ""
    body = {
        "authCode": userAuthCode,
        "clientId": settings.WP_APP_KEY,
        "clientSecret": settings.WP_APP_SECRET,
        "grantType": "authorization_code",
        "redirectUri": settings.WP_REDIRECT_URI,
    }
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': 'eyJhbGciOiJIUzUxMiJ9.eyJjbGllbnRJZCI6ImFrXzh4OXkyYjdtNG42ZDNwNXExcjBzIiwic2NvcGUiOiJyZWFkIiwiZXhwIjoxNzYyNDE4MTYzLCJ1c2VySWQiOjE5ODYyNjMwNDQ1NTQ1Njc2ODIsImlhdCI6MTc2MjQxMDk2M30.ZBols8YVbNTPgEypNmkY_jm4bcxV6z63oajoGv-8yWjwdcYcu5B81CpUAD2W7_SECHV0wGw4iy9h4V7uTTuD1Q', 'rc': 0, 'success': True}
    return response

async def get_wp_user_info(accessToken: str):
    """获取WaveUp用户信息"""
    path = settings.WP_GET_USER_INFO
    query = ""
    body = {
        "accessToken": accessToken,
    }
    body_str = json.dumps(body).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    # {'data': {'userOpenId': '1986263044554567682', 'mobileNo': '13632850648', 'nickName': '藏家_97****qcsz', 'avatar': 'https://mdn.alipayobjects.com/chain_myent/afts/img/QRouTrmogzcAAAAAAAAAAAAADvN2AQBr/original', 'kycStatus': 0}, 'rc': 0, 'success': True}
    return response

async def query_user_asset_list(
    productId: str,
    userOpenId: str,
    pageNo: int = 1, 
    pageSize: int = 100, 
):
    """查询WaveUp用户资产列表"""
    path = settings.WP_QUERY_USER_ASSET_LIST
    query = ""
    body = {
        "productId": productId,
        "userOpenId": userOpenId,
        "pageNo": pageNo,
        "pageSize": pageSize,
    }
    body_str = json.dumps(body, sort_keys=True).replace(" ", "") # 参与签名是，query和body都不能有空格
    signature = await generate_signature(path, query, body_str)
    headers = {
        "Authorization": signature,
        "Content-Type": "application/json"
    }
    url = f"{settings.WP_API_URL}{path}?{query}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=body
    )
    return response
